package org.keyroy.map_editor.project;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.keyory.map_editor.system.Environments;
import org.keyroy.map_editor.map.Map;
import org.keyroy.util.file.FileUtil;

public class Project {
	private static final String MAP_TAG = "edit_map";

	private static final String SHARE = "share";
	private static final String MAPS = "maps";

	private static final String SHARE_FLOORS = "floors";
	private static final String SHARE_BULIDINGS = "buildings";
	private static final String SHARE_SPRITES = "sprites";

	private File root;

	public Project(File file) throws Exception {
		root = file;

		FileUtil.makeFolder(root);
		FileUtil.makeFolder(new File(root, MAPS));
		File share = new File(root, SHARE);
		FileUtil.makeFolder(share);

		FileUtil.makeFolder(new File(share, SHARE_FLOORS));
		FileUtil.makeFolder(new File(share, SHARE_BULIDINGS));
		FileUtil.makeFolder(new File(share, SHARE_SPRITES));

	}

	public Map createMap(String name, int columns, int rows, int pWidth, int pHeight, boolean used45) {
		File file = new File(root, MAPS);
		File folder = new File(file, name);
		FileUtil.makeFolder(folder);
		Map currentMap = new Map(columns, rows, pWidth, pHeight, folder, used45);
		return currentMap;
	}

	public List<String> listMap() {
		List<String> strings = new ArrayList<String>();
		File folder = new File(root, MAPS);
		File[] files = folder.listFiles();
		for (int i = 0; i < files.length; i++) {
			File mapXml = new File(files[i], "Map");
			if (mapXml.exists()) {
				strings.add(files[i].getName());
			}
		}

		return strings;
	}

	public Map openMap(String mapPath) {
		try {
			File folder = new File(root, MAPS);
			return new Map(new File(folder, mapPath));
		} catch (Exception e) {
		}

		return null;
	}

	public boolean deleteMap(String mapPath) {
		try {
			File folder = new File(root, MAPS);
			File file = new File(folder, mapPath);

			if (file.delete()) {
				FileUtil.deleteIni(MAP_TAG);
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
		}

		return false;
	}

	public String getNewMapName() {
		int i = 1;
		File folder = new File(root, MAPS);
		while (true) {
			File mapFolder = new File(folder, "m" + i);
			if (mapFolder.exists() == false) {
				return "m" + i;
			} else {
				i++;
			}
		}
	}

	public File getFolder() {
		return root;
	}

	public void save() {
		if (Environments.getCurrentEditMap() != null) {
			Environments.getCurrentEditMap().save();
		}
	}

	public static final Project open(File file) {
		if (file != null) {
			try {
				return new Project(file);
			} catch (Exception e) {
			}
		}
		return null;
	}
}
